﻿using Framework.Utility.Excel;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using YouShuCode;
using YouShuCode.Models;
using YouShuCode.Utils;

namespace DevSupport.Areas.YouShu
{
    [ApiController]
    public class YouShuController : ControllerBase
    {
        private readonly ILogger<YouShuController> _logger;
        private readonly IYouShuService _service;

        public YouShuController(ILogger<YouShuController> logger, IYouShuService service)
        {
            _logger = logger;
            _service = service;
        }
        /// <summary>
        /// 下载批量查询模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("api/YouShu/DownLoadTemp")]
        public IActionResult Get()
        {
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "UploadFiles/Temp/导入模板.xlsx");
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, bytes.Length);
            fileStream.Close();
            var contentType = "application/octet-stream";
            var _files = File(bytes, contentType);
            return _files;
        }

        /// <summary>
        /// 单条查询
        /// </summary> 
        /// <returns>excel</returns>
        [HttpPost]
        [Route("api/YouShu/QueryDetail")]
        public IActionResult QueryDetail([FromBody] YouShuRequest param)
        {
            var data = _service.EnterpriseApi(param.EntInfo, param.UserName);

            return Ok(data);
        }
        /// <summary>
        /// 单条查询并且导出到excel
        /// </summary>
        /// <param name="EntInfo">企业信息</param>
        /// <param name="UserName">操作用户</param>
        /// <returns>excel</returns>
        [HttpGet]
        [Route("api/YouShu/QueryInfo")]
        public IActionResult Get(string EntInfo, string UserName)
        {
            if (string.IsNullOrEmpty(EntInfo)) return Ok("请输入企业信息！");
            var successList = new List<object>();
            var errorList = new List<object>();
            var data = _service.EnterpriseApi(EntInfo, UserName);
            if (data.IsSuccess)
            {
                var apiResponse = JsonHelper.FromJson<ResponseData>(data.ApiResponse);
                successList.Add(apiResponse.data.basicList[0]);
            }
            else
            {
                errorList.Add(new ErrorResponseDTO
                {
                    UserName = UserName,
                    EntInfo = EntInfo,
                    ErrorCode = data.ErrorCode,
                    IsSuccess = data.IsSuccess,
                    Message = data.Message
                });
            }
            var fileName = $"报表_{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xls";
            List<ExcelDataResource> dataResources = new List<ExcelDataResource>() {
                new ExcelDataResource(){
                    SheetName ="成功查询",
                    TitleIndex = 1,
                    SheetDataResource = successList
                },
                 new ExcelDataResource(){
                    SheetName ="失败查询",
                    TitleIndex = 1,
                    SheetDataResource = errorList
                }
            };

            IWorkbook workbook = ExcelHelper.DataToHSSFWorkbook(dataResources);

            #region 服务器备份

            var fileFolder = Path.Combine(Directory.GetCurrentDirectory(), "Downloads");
            var filePath = Path.Combine(fileFolder, fileName);
            using (FileStream file = new FileStream(filePath, FileMode.Create))
            {
                workbook.Write(file);
            }

            #endregion 服务器备份

            byte[] barray;
            using (var stream = new MemoryStream())
            {
                workbook.Write(stream);
                barray = stream.ToArray();
                stream.Close();
            }
            var contentType = "application/x-excel";
            _logger.LogInformation($"操作人：{UserName},EntInfo：{EntInfo}，报表：{fileName}");
            return File(barray, contentType, fileName);
        }

        /// <summary>
        /// 批量查询并且导出到excel
        /// </summary>
        /// <param name="file">查询的Excel</param>
        /// <returns>excel</returns>
        [HttpPost]
        [Route("api/YouShu/BatchQuery")]
        public IActionResult DownLoadFile(IFormFile file)
        {
            string extension = Path.GetExtension(file.FileName);
            if (!extension.Contains("xls") && !extension.Contains("xlsx")) return Ok("上传的文件格式不正确！仅支持.xls与.xlsx格式");
            BKFiletoServer(file);

            var fileFolder = Path.Combine(Directory.GetCurrentDirectory(), "Downloads");
            if (!Directory.Exists(fileFolder))
                Directory.CreateDirectory(fileFolder);

            var fileName = $"报表_{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xls";
            var filePath = Path.Combine(fileFolder, fileName);

            var listData = new List<BK_Contact>();
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                file.CopyTo(stream);
                var dt = ExcelHelper.ExcelStreamToDataTable(stream).FirstOrDefault();
                listData = dt != null ? dt.ConvertDataTableToList<BK_Contact>() : new List<BK_Contact>();
            }

            listData = listData.Where(c => !string.IsNullOrWhiteSpace(c.Column4_CompanyName)).ToList();
            if (!listData.Any()) return Ok("Excel中的数据不匹配或Excel为空！");
            var successList = new List<object>();
            var errorList = new List<object>();
            foreach (var item in listData)
            {
                if (string.IsNullOrWhiteSpace(item.Column4_CompanyName)) continue;
                var data = _service.EnterpriseApi(item.Column4_CompanyName, item.Column2_Name);
                Thread.Sleep(500);
                if (data.IsSuccess)
                {
                    var apiResponse = JsonHelper.FromJson<ResponseData>(data.ApiResponse).data.basicList[0];
                    var comp = listData.FirstOrDefault(c => c.Column4_CompanyName == apiResponse.EntName);
                    if (comp != null)
                    {
                        apiResponse.Column1_DirectSellerID = comp.Column1_DirectSellerID;
                        apiResponse.Column2_Name = comp.Column2_Name;
                    }
                    successList.Add(apiResponse);
                }
                else
                {
                    errorList.Add(new ErrorResponseDTO
                    {
                        UserName = item.Column2_Name,
                        EntInfo = item.Column4_CompanyName,
                        ErrorCode = data.ErrorCode,
                        IsSuccess = data.IsSuccess,
                        Message = data.Message
                    });
                }
            }

            List<ExcelDataResource> dataResources = new List<ExcelDataResource>() {
                new ExcelDataResource(){
                    SheetName ="成功查询",
                    TitleIndex = 1,
                    SheetDataResource = successList
                },
                 new ExcelDataResource(){
                    SheetName ="失败查询",
                    TitleIndex = 1,
                    SheetDataResource = errorList
                }
            };

            IWorkbook workbook = ExcelHelper.DataToHSSFWorkbook(dataResources);

            byte[] barray;
            using (var stream = new MemoryStream())
            {
                workbook.Write(stream);
                barray = stream.ToArray();
                stream.Close();
            }
            //var contentType = "application/x-excel";
            var contentType = "application/octet-stream";
            _logger.LogInformation($"导入报表：{file.FileName},导出报表：{fileName}");
            return File(barray, contentType, fileName);
        }

        private void BKFiletoServer(IFormFile file)
        {
            var uploadFolder = Path.Combine(Directory.GetCurrentDirectory(), "UploadFiles");

            #region 保存上传文件

            if (!Directory.Exists(uploadFolder))
                Directory.CreateDirectory(uploadFolder);

            var uploadFile = Path.Combine(uploadFolder, file.FileName);

            using (FileStream fl = new FileStream(uploadFile, FileMode.Create))
            {
                file.CopyTo(fl);
            }

            #endregion 保存上传文件
        }
    }
}